import random
import re

from flask import current_app
from flask import make_response
from flask import request, jsonify
from flask import session

from info import redis_store, db
from info.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from info.models import User
from info.utils.response_code import RET
from info.utils.captcha.captcha import captcha
from . import passport_blu
from info.libs.yuntongxun.sms import CCP
@passport_blu.route("/image_code")
def image_code():

    imageCodeId = request.args.get('imageCodeId')
    if not imageCodeId:
        return jsonify(errno=RET.PARAMERR, errmsg='传入参数错误')

    name, text, image = captcha.generate_captcha()
    print(text)
    try:
        redis_store.setex('imageCodeId_'+imageCodeId, IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'
    return response

@passport_blu.route("/sms_code", methods=["POST"])
def send_sms_code():
    # 'mobile': mobile,
    # 'imageCode': imageCode,
    # 'imageCodeId': imageCodeId
    mobile = request.json.get('mobile')
    imageCode = request.json.get('imageCode')
    imageCodeId = request.json.get('imageCodeId')
    print(imageCode)
    if not all([mobile, imageCode, imageCodeId]):
        return jsonify(errno=RET.PARAMERR, errmsg='接受参数不完整')
    if not re.match(r"1[3456789]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号不符合规则")
    try:
        real_imageCode = redis_store.get('imageCodeId_'+imageCodeId)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库读取数据失败')
    if not real_imageCode:
        return jsonify(errno=RET.DATAEXIST, errmsg='验证码已经过期')
    try:
        redis_store.delete('imageCodeId_'+imageCodeId)
    except Exception as e:
        current_app.logger.error(e)
    if real_imageCode.lower() != imageCode.lower():
        return jsonify(errno=RET.DATAERR, errmsg='输入的验证码错误')
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库读取信息失败')
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机已经注册`')
    try:
        sms_code = '%06d' % random.randint(0, 999999)
        redis_store.setex('sms_code_'+ mobile, SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存验证码失败')
    try:
        ccp = CCP()
        result = ccp.send_template_sms(mobile, [sms_code, SMS_CODE_REDIS_EXPIRES/300], 1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='发送验证码失败')
    if result == 0:
        return jsonify(errno=RET.OK, errmsg='发送成功')
    else:
        return jsonify(errno=RET.THIRDERR, errmsg="发送失败")

@passport_blu.route("/register", methods=["POST"])
def make_register():
    mobile = request.json.get('mobile')
    sms_code = request.json.get('sms_code')
    password = request.json.get('password')
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='接受参数错误')
    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='接受的手机号不符合规则')
    try:
        real_sms_code = redis_store.get('sms_code_'+ mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='读取数据库失败')
    if not real_sms_code:
        return jsonify(errno=RET.DATAEXIST, errmsg='验证码已过期')
    try:
        redis_store.delete('sms_code_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
    if real_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg='输入的验证码有误')
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='读取数据库信息失败')
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='用户已经注册')
    if len(password) < 6:
        return jsonify(errno=RET.PARAMERR, errmsg='密码不符合规则')
    try:
        user = User()
        user.mobile = mobile
        user.nick_name = mobile
        user.password = password
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存用户信息失败')
    else:
        session['user_id'] = user.id
        session['user_name'] = mobile
        session['mobile'] = mobile
        return jsonify(errno=RET.OK, errmsg='注册成功')


@passport_blu.route("/logout")
def make_logout():
    session.pop('user_id')
    session.pop('user_name')
    session.pop('mobile')
    return jsonify(errno=RET.OK, errmsg="退出登入")

@passport_blu.route("/login", methods=["POST"])
def make_login():
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='接受参数错误')
    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询数据失败')
    if not user or not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg='手机号或者密码错误')
    else:
        session['user_id'] = user.id
        session['user_name'] = user.nick_name
        session['mobile'] = user.mobile
        return jsonify(errno=RET.OK, errmsg='用户登入成功')




















































